<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page -->
<route lang="jsonc" type="home">
{
  "layout": "tabbar",
  "style": {
    // 'custom' 表示开启自定义导航栏，默认 'default'
    "navigationStyle": "custom",
    "navigationBarTitleText": "首页"
  }
}
</route>

<script lang="ts" setup>
import logger from '@/js_sdk/walker-logger/walker-logger/walker-logger'

defineOptions({
  name: 'Home',
})

// 连接 WiFi
// async function customConnectToWifi(wifi) {
//   if (!plus.android) {
//     uni.showToast({ title: 'plus 环境未加载', icon: 'none' })
//     return
//   }

//   const Context = plus.android.importClass('android.content.Context') as any
//   plus.android.importClass('android.net.wifi.WifiManager')
//   const WifiConfiguration = plus.android.importClass('android.net.wifi.WifiConfiguration') as any
//   const mainActivity = plus.android.runtimeMainActivity() as any
//   const wifiManager = mainActivity.getSystemService(Context.WIFI_SERVICE)

//   console.log('123')

//   // 创建 WiFi 配置
//   const wifiConfig = new WifiConfiguration()

//   console.log('wifiConfig 创建成功:', wifiConfig)

//   console.log('666')
//   wifiConfig.SSID = `"${wifi.SSID}"` // SSID 需要加双引号
//   console.log('wifi.SSID: ', wifi.SSID)
//   console.log('777')
//   wifiConfig.preSharedKey = `"yixin666888"` // 密码需要加双引号（WPA/WPA2）
//   wifiConfig.status = WifiConfiguration.Status.ENABLED
//   console.log('WifiConfiguration.Status.ENABLED: ', WifiConfiguration.Status.ENABLED)

//   // 检查 allowedKeyManagement 是否可用
//   console.log('wifiConfig.allowedKeyManagement: ', wifiConfig.allowedKeyManagement)

//   if (!wifiConfig.allowedKeyManagement) {
//     uni.showToast({ title: 'allowedKeyManagement 不可用', icon: 'none' })
//     return
//   }

//   console.log('888')
//   // wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK) // 设置加密方式为 WPA/WPA2

//   console.log('(WifiConfiguration.KeyMgmt.WPA_PSK: ', WifiConfiguration.KeyMgmt.WPA_PSK)

//   // 添加 WiFi 配置
//   const networkId = wifiManager.addNetwork(wifiConfig)
//   console.log('networkId: ', networkId)

//   console.log('789')

//   if (networkId === -1) {
//     uni.showToast({ title: 'WiFi 配置失败', icon: 'none' })
//     return
//   }

//   // 断开当前连接并连接新网络
//   wifiManager.disconnect()

//   const success = wifiManager.enableNetwork(networkId, true)
//   console.log('success: ', success)
//   if (success) {
//     wifiManager.reconnect()
//     uni.showToast({ title: `${wifi.SSID} 连接中...`, icon: 'loading' })
//   }
//   else {
//     uni.showToast({ title: 'WiFi 连接失败', icon: 'none' })
//   }
// }

function requestPermissions() {
  if (plus.os.name.toLowerCase() === 'android') {
    plus.android.requestPermissions(
      [
        'android.permission.ACCESS_FINE_LOCATION',
        'android.permission.ACCESS_COARSE_LOCATION',
      ],
      (res) => {
        if (res.deniedAlways.length > 0) {
          uni.showModal({ title: '权限被永久拒绝，请手动开启', icon: 'none' })
          console.log('xxxxxxxxxxxxx ', '权限被永久拒绝，请手动开启')
        }
        else {
          uni.showModal({
            title: '去连接目标 WiFi逻辑',
            icon: 'none',
            success() {
              console.log('success: 来了来了')

              try {
                // customConnectToWifi({ SSID: '一心自习室' })

                uni.startWifi({
                  success() {
                    uni.connectWifi({
                      SSID: '一心自习室',
                      password: 'yixin666888',
                      maunal: false,

                      success() {
                        console.log('连接目标热点成功')
                        logger.info(`连接目标热点成功`)
                        uni.showModal({ title: `连接目标热点成功`, icon: 'success' })
                      },

                      fail(err) {
                        console.log('err: ', err)
                        logger.info(`连接目标热点成功失败:${JSON.stringify(err)}`)
                        uni.showModal({ title: `${err.errCode}`, icon: 'none' })
                      },

                    })
                  },

                  fail(err) {
                    console.log('startWifi err: ', err)
                  },
                })
              }
              catch (error) {
                console.log('error: -------', error)
              }
            },
          })
          console.log('去连接目标 WiFi逻辑: ')
        }
      },
      (err) => { console.error('权限请求失败', err) },
    )
  }
}

// 状态管理
const wifiList = ref<any[]>([])
const password = ref('')

// 动态申请权限
function requestAndroidPermission(permissionID) {
  return new Promise((resolve) => {
    plus.android.requestPermissions(
      [permissionID],
      (resultObj) => {
        let result = 0
        if (resultObj.granted.length > 0) {
          result = 1 // 已授权
        }
        else if (resultObj.deniedPresent.length > 0) {
          result = 0 // 本次拒绝
        }
        else if (resultObj.deniedAlways.length > 0) {
          result = -1 // 永久拒绝
        }
        resolve(result)
      },
      (error) => {
        resolve({ code: error.code, message: error.message })
      },
    )
  })
}

// 跳转到权限设置页面
function gotoAppPermissionSetting() {
  const Intent = plus.android.importClass('android.content.Intent') as any
  const Settings = plus.android.importClass('android.provider.Settings') as any
  const Uri = plus.android.importClass('android.net.Uri') as any
  const mainActivity = plus.android.runtimeMainActivity() as any
  const intent = new Intent()
  intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
  const uri = Uri.fromParts('package', mainActivity.getPackageName(), null)
  intent.setData(uri)
  mainActivity.startActivity(intent)
}

// 检查定位权限
async function isPermission() {
  const res = await requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION')
  if (res === 1)
    return true
  uni.showToast({ title: '请开启定位权限', icon: 'none' })
  gotoAppPermissionSetting()
  return false
}

// 初始化 WiFi 模块
function initWifi() {
  return new Promise((resolve, reject) => {
    uni.startWifi({
      success: () => {
        console.log('WiFi 模块初始化成功')
        resolve(true)
      },
      fail: (e) => {
        console.error('WiFi 模块初始化失败', e)
        uni.showToast({ title: 'WiFi 初始化失败', icon: 'none' })
        reject(e)
      },
    })
  })
}

// 初始化 WiFi
async function startWifi() {
  const hasPermission = await isPermission()
  if (!hasPermission)
    return
  await initWifi()
}

// 获取 WiFi 列表
function getWifiList() {
  return new Promise((resolve, reject) => {
    uni.getWifiList({
      success: () => {
        console.log('获取 WiFi 列表命令发送成功')
        uni.onGetWifiList((res) => {
          const list = res.wifiList
            .filter(item => item.SSID)
            .sort((a, b) => b.signalStrength - a.signalStrength)
          console.log('WiFi 列表', list)
          resolve(list)
        })
      },
      fail: (e) => {
        console.error('获取 WiFi 列表失败', e)
        uni.showToast({ title: e.errMsg, icon: 'none' })
        reject(e)
      },
    })
  })
}

// 扫描 WiFi
async function scanWifi() {
  wifiList.value = await getWifiList() as any
}

// 连接 WiFi
function connectWifi(ssid, password, bssid = '') {
  return new Promise((resolve, reject) => {
    uni.connectWifi({
      SSID: ssid,
      BSSID: bssid,
      password,
      partialInfo: true,
      maunal: false,
      success: (res) => {
        if (res.errCode === 0) {
          uni.showToast({ title: `${ssid} 连接成功`, icon: 'success' })
          resolve(res)
        }
      },
      fail: (e) => {
        let msg
        switch (e.errCode) {
          case 12002:
            msg = 'WiFi 密码错误'
            break
          case 12005:
            msg = 'WiFi 未开启'
            break
          case 12013:
            msg = 'WiFi 配置过期，请重新尝试'
            break
          default:
            msg = e.errMsg
        }
        uni.showToast({ title: msg, icon: 'none' })
        reject(e)
      },
    })
  })
}

// 连接指定 WiFi
async function connectToWifi(wifi) {
  if (!password.value) {
    uni.showToast({ title: '请输入密码', icon: 'none' })
    return
  }
  await connectWifi(wifi.SSID, password.value, wifi.BSSID)
}
</script>

<template>
  <view class="bg-white px-4 pt-2" :style="{ marginTop: `30px` }">
    <view class="mb-8 mt-2 text-center text-2xl">
      最好用的 uniapp 开发模板
    </view>

    <view class="container">
      <wd-button @click="startWifi">
        初始化 WiFi
      </wd-button>

      <wd-button @click="scanWifi">
        扫描 WiFi
      </wd-button>

      <wd-button plain custom-class="!ml-10rpx" @click="requestPermissions">
        测试原生的
      </wd-button>

      <view v-for="(wifi, index) in wifiList" :key="index" class="wifi-item" @click="connectToWifi(wifi)">
        {{ wifi.SSID }} (信号强度: {{ wifi.signalStrength }})
      </view>
      <input v-model="password" placeholder="请输入 WiFi 密码">
    </view>
  </view>
</template>
